package com.bloveoa.zkkd.service.impl;

import com.bloveoa.zkkd.doman.BoxInfoModel;
import com.bloveoa.zkkd.doman.UserModel;
import com.bloveoa.zkkd.repository.BoxInfoRepository;
import com.bloveoa.zkkd.repository.UserRepository;
import com.bloveoa.zkkd.service.BoxInfoService;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.function.Consumer;

@Service
public class BoxInfoServiceImpl implements BoxInfoService {

    private final BoxInfoRepository outTokenRepository;
    private final UserRepository userRepository;


    public BoxInfoServiceImpl(BoxInfoRepository outTokenRepository, UserRepository userRepository) {
        this.outTokenRepository = outTokenRepository;
        this.userRepository = userRepository;
    }


    public void saveAll(List<BoxInfoModel> datas) {
        outTokenRepository.saveAll(datas);
    }

    public void updateOrInsert(List<BoxInfoModel> datas) {
        datas.forEach(new Consumer<BoxInfoModel>() {
            @Override
            public void accept(BoxInfoModel boxInfoModel) {
                if (outTokenRepository.existsBoxInfoModelByTMac(boxInfoModel.getTMac())) {
                    //如果用户存在就把数量加到user列表中
                    if (userRepository.existsByBoxMac(boxInfoModel.getTMac())) {
                        UserModel userModel = userRepository.queryByBoxMac(boxInfoModel.getTMac());
                        userModel.setTokenNum(userModel.getTokenNum()+boxInfoModel.getTokenNun());
                        userRepository.save(userModel);
                        outTokenRepository.update(boxInfoModel.getTokenNun(), boxInfoModel.getTOnLong(), boxInfoModel.getTOpenTims(), boxInfoModel.getTMac());
                    } else {
                        outTokenRepository.update((boxInfoModel.getTokenNun() + outTokenRepository.queryByTMac(boxInfoModel.getTMac()).getTokenNun()), boxInfoModel.getTOnLong(), boxInfoModel.getTOpenTims(), boxInfoModel.getTMac());
                    }
                } else {
                    outTokenRepository.save(boxInfoModel);
                }
            }
        });
    }
}
